import datetime
import logging
import os
import time
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch import *

import html5lib

class MainHandler(webapp.RequestHandler):
    def get(self):
         self.response.out.write('<html><body>')
         self.response.out.write("""
           <form action="/" method="post">
            <div>Address: <input name="url" size="50"></input><input type="submit" value="Check"></div>
           </form>
         </body>
       </html>""")

    def post(self):
         url = self.request.get("url")
         if url.find("http://") == -1 or url.find("https://") == -1:
             url = "http://"+url
         self.response.out.write('<html><body>')
         self.response.out.write("""
           <form action="/" method="post">
            <div>Address: <input name="url" size="50"></input><input type="submit" value="Check"></div>
           </form>
         </body>
       </html>""")
         try:
             result = urlfetch.fetch(url)
         except InvalidURLError:
             self.response.out.write("<div>Invalid Url address:"+url+"</div>")
         else:
             self.response.out.write("<h1><a href='"+url+"'>"+url+"</a></h1>")
             self.response.out.write("<h2>Header information</h2>")
             result = urlfetch.fetch(url)
             if result.status_code == 200:
                 for name, value in result.headers.items():
                     self.response.out.write("<div><span><strong>"+name+"</strong>:</span>")
                     self.response.out.write("<span>"+value+"</span></div>")
                 parser = html5lib.HTMLParser()
                 document = parser.parse(result.content)  
                     
if __name__ == '__main__':
  application = webapp.WSGIApplication(
      [
        ('/', MainHandler),
      ],
      debug = True)

  wsgiref.handlers.CGIHandler().run(application)
